package com.xbjtech.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Seller;
import com.xbjtech.model.beans.Result;
import com.xbjtech.realm.CustomRealm;
import com.xbjtech.redis.RedisUtils;
import com.xbjtech.service.SellerService;

@Controller
@RequestMapping("/seller")
public class SellerController {
	
	@Autowired
	SellerService sellerService;
	
	@Autowired
	RedisUtils redisUtils;

	@RequestMapping("/list")
	public String list() {
		return "seller/list";
	}
	
	
	@GetMapping("/data")
	@ResponseBody
	public Map<String, Object> data(
			@RequestParam(value = "page", required = false, defaultValue = "1")
			Integer page,
			@RequestParam(value = "rows", required = false, defaultValue = "10")
			Integer rows
			) {
		PageInfo<Seller> sellers = sellerService.selectByExamplePage(page, rows, null);
		Map<String, Object> map = new HashMap<>();
		map.put("total", sellers.getTotal());
		map.put("rows", sellers.getList());
		return map;
	}
	
	@PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result save(@Validated Seller seller, Errors errors) {
		// 服务器端校验
		// errors还需要处理一下
		try {
			if (null == seller.getId()) {
				sellerService.insertWithoutPrimaryKey(seller);
			} else {
				sellerService.updateByPrimaryKey(seller);
			}
			return Result.success();
		} catch (Exception e) {
		}
		return Result.fail();
	}
	
	@Autowired
	CustomRealm customRealm;
	
	@GetMapping("/del")
	@ResponseBody
	public Result del(
			@RequestParam(value = "id", required = true)
			Integer id) {
		try {
			sellerService.deleteByPrimaryKey(id);
			return Result.success();
		} catch (Exception e) {
		}
		return Result.fail();
	}
	
	static String json1 = null;
	
	@GetMapping("/getSellers")
	@ResponseBody
	public String getSellers() {
		// 作缓存
		String key = "sellers_list";
		byte[] bs = redisUtils.get(key.getBytes());
		if (bs == null) {
			// 缓存里面数据失效或者从来就没有过
			synchronized (this) {
				String json = null;
				byte[] bytes = redisUtils.get(key.getBytes());
				if (bytes == null) {
					List<Seller> sellers = sellerService.selectAll();
					json = JSON.toJSONString(sellers);
					redisUtils.set(key.getBytes(), json.getBytes(), 24 * 60 * 60);
				} else {
					json = new String(bytes);
				}
				return json;
			}
		} else {
			return new String(bs);
		}
	}
}
